﻿using DataAcquisition;
using gl_SMT.Model;
using SMTUploadProductionData.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace gl_SMT.View
{
    /// <summary>
    /// UserControlMachine.xaml 的交互逻辑
    /// </summary>
    public partial class UserControlMachine : UserControl
    {
        public UserControlMachine()
        {
            InitializeComponent();
            this.Loaded += UserControlMachine_Loaded;
            
        }

        List<MachineModel> lsit_machineModels = new List<MachineModel>();
        List<string> list_gkg_MachineName = new List<string>() { "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10", "A11", "A12", };
        List<string> list_hl_MachineName = new List<string>() { "1号机", "2号机", "3号机" };
        List<string> list_ymh_MachineName = new List<string>() { "雅马哈_1号机", "雅马哈_2号机", "雅马哈_3号机", "雅马哈_4号机", "雅马哈_5号机", "雅马哈_6号机" };
        List<string> list_juki_MachineName = new List<string>() { "juki 1号机", "juki 2号机", };
        DatabaseReadWrite database = new DatabaseReadWrite();
        private volatile bool Running = true;
        private void UserControlMachine_Loaded(object sender, RoutedEventArgs e)
        {
            if (Running)
            {
                AddEquipment();
                Task.Run(() => ShowData(VariableStorage.SelectType));
                Running = false;
            }
        }

        private void AddEquipment()
        {
            for (int i = 0; i < VariableStorage.NumberMachines; i++)
            {
                //MachineModel为自定义控件
                MachineModel model = new MachineModel();
                //定义MachineModel的Name
                model.ControlName = "MachineTable" + i.ToString();
                //添加显示控件
                Panel_ModelSelection.Children.Add(model);
                //添加全部的机台
                lsit_machineModels.Add(model);
            }

        }

        /// <summary>
        /// 每台机型的数据显示
        /// </summary>
        public async Task ShowData(string Type)
        {
            switch (Type)
            {
                case "GKG自动印刷机":
                    await gkg_DataUpdate();
                    break;
                case "回流焊接机":
                    await hl_DataUpdate();
                    break;
                case "雅马哈贴片机":
                    await ymh_DataUpdate();
                    break;
                case "JUKI贴片机":
                    await juki_DataUpdate();
                    break;
                default:
                    break;
            }
        }

        #region  gkg自动印刷机
        private async Task gkg_DataUpdate()
        {
            while (VariableStorage.gkg_Running) 
            {
                try
                {
                    List<gkg_model> gkg_Models = new List<gkg_model>();
                    await database.SelectDataAsync(gkg_Models);
                    List<string> OnTime = gkg_MachineOnTime();
                    for (int i = 0; i < list_gkg_MachineName.Count; i++)
                    {
                        int index = gkg_IndexName(list_gkg_MachineName[i], gkg_Models);
                        if (index == -1) 
                        {
                            Dispatcher.Invoke(() =>
                            {
                                lsit_machineModels[i].txt_Model.Text = list_gkg_MachineName[i];
                                lsit_machineModels[i].txt_Model.Tag = "GKG自动印刷机";
                            });
                            continue; 
                        }
                        await Dispatcher.Invoke(async () =>
                        {
                            lsit_machineModels[i].txt_Model.Text = list_gkg_MachineName[i];
                            lsit_machineModels[i].txt_Model.Tag = "GKG自动印刷机";
                            lsit_machineModels[i].txt_ProductName.Text = gkg_Models[index].FileName;//产品名称;
                            lsit_machineModels[i].txt_Cycle.Text = gkg_Models[index].CycleTime + "(s)";//生产周期
                            lsit_machineModels[i].txt_Output.Text = gkg_Models[index].PCBNumber.ToString() + "(pcs)";//生产数量
                            lsit_machineModels[i].txt_OnTime.Text = OnTime[i];//开机时间
                            lsit_machineModels[i].txt_EquipmentAlm.Text = "0";//报警数量
                            lsit_machineModels[i].btn_Line.Content = "在线";
                            lsit_machineModels[i].btn_Line.Background = Brushes.Green;
                            lsit_machineModels[i].txt_EquipmentAlm.Text = await gkg_EquipmentAlm(gkg_Models[index].MachineName);
                        });
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    continue;
                }
                await Task.Delay(3000);
            }
        }

        private int gkg_IndexName(string gkgMachineName, List<gkg_model> gkg_Models)
        {
            for (int i = 0; i < gkg_Models.Count; i++)
            {
                if (gkgMachineName == gkg_Models[i].MachineName)
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// gkg开机时间
        /// </summary>
        /// <returns></returns>
        private List<string> gkg_MachineOnTime()
        {
            List<string> list_Time = new List<string>();
            TimeSpan timeSpan = TimeSpan.FromSeconds(0);
            for (int i = 0; i < list_gkg_MachineName.Count; i++)
            {
                timeSpan = TimeSpan.FromSeconds(0);
                List<gkg_model> list_gkg = new List<gkg_model>();
                database.SelectData(ref list_gkg, "gkg_Producedate", "MachineName", list_gkg_MachineName[i]);
                foreach (var gkg in list_gkg)
                {
                    timeSpan += TimeSpan.FromSeconds(int.Parse(gkg.CycleTime));
                }
                int totalHours = (int)timeSpan.TotalHours;
                string formattedTime = $"{totalHours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}";
                list_Time.Add(formattedTime);
            }
            return list_Time;
        }

        private async Task<string> gkg_EquipmentAlm(string name)
        {
            List<gkg_Event_model> gkg_Event=await database.SelectEvent(name);
            return gkg_Event.Count.ToString();
        }
        #endregion

        #region  回流焊接机
        private async Task hl_DataUpdate()
        {
            while (VariableStorage.hl_Running) 
            {
                List<hl_model> hl_Models = new List<hl_model>();
                await database.SelectDataAsync(hl_Models);
                List<string> OnTime = hl_MachineOnTime();
                for (int i = 0; i < hl_Models.Count; i++)
                {
                    int index = hl_IndexName(list_hl_MachineName[i], hl_Models);
                    if (index == -1) 
                    { 
                        Dispatcher.Invoke(() => 
                        { 
                            lsit_machineModels[i].txt_Model.Text = list_hl_MachineName[i];
                            lsit_machineModels[i].txt_Model.Tag = "回流焊接机";
                        }); 
                        continue; 
                    }
                    Dispatcher.Invoke(() =>
                    {
                        lsit_machineModels[i].txt_Model.Text = list_hl_MachineName[i];
                        lsit_machineModels[i].txt_Model.Tag = "回流焊接机";
                        lsit_machineModels[i].tb_Model.Text = "供电状态";
                        lsit_machineModels[i].txt_ProductName.Text = hl_Models[index].PowerSupply;
                        lsit_machineModels[i].tb_MachineStatus.Text = "机器状态";
                        lsit_machineModels[i].txt_Cycle.Text = hl_Models[index].Machine;
                        lsit_machineModels[i].tb_HotAirMotor.Text = "热风马达";
                        lsit_machineModels[i].txt_Output.Text = hl_Models[index].HotAirMotor;//生产数量
                        lsit_machineModels[i].txt_OnTime.Text = OnTime[i];//开机时间
                        lsit_machineModels[i].txt_EquipmentAlm.Text = "0";//报警数量
                        lsit_machineModels[i].btn_Line.Content = "在线";
                        lsit_machineModels[i].btn_Line.Background = Brushes.Green;
                    });
                }
                await Task.Delay(3000);
            }
        }

        private int hl_IndexName(string gkgMachineName, List<hl_model> hl_Models)
        {
            for (int i = 0; i < hl_Models.Count; i++)
            {
                if (gkgMachineName == hl_Models[i].MachineName)
                {
                    return i;
                }
            }
            return -1;
        }
        private List<string> hl_MachineOnTime()
        {
            List<string> list_Time = new List<string>();
            TimeSpan timeSpan = TimeSpan.FromSeconds(0);
            for (int i = 0; i < list_hl_MachineName.Count; i++)
            {
                timeSpan = TimeSpan.FromSeconds(0);
                List<hl_model> list_hl = new List<hl_model>();
                database.SelectData(ref list_hl, "hl_Producedate", "MachineName", list_hl_MachineName[i]);
                timeSpan = TimeSpan.FromSeconds(list_hl.Count * (5 * 60));
                int totalHours = (int)timeSpan.TotalHours;
                string formattedTime = $"{totalHours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}";
                list_Time.Add(formattedTime);
            }
            return list_Time;
        }
        #endregion

        #region  雅马哈贴片机
        private async Task ymh_DataUpdate()
        {
            while (VariableStorage.ymh_Running) 
            {
                try
                {
                    List<ymh_model> ymh_Model = new List<ymh_model>();
                    await database.SelectDataAsync(ymh_Model);
                    List<string> OnTime = await ymh_MachineOnTime();
                    List<string> list_Total = await ymh_Total();
                    for (int i = 0; i < ymh_Model.Count; i++)
                    {
                        int index = ymh_IndexName(list_ymh_MachineName[i], ymh_Model);
                        if (index == -1) 
                        { 
                            Dispatcher.Invoke(() => 
                            { 
                                lsit_machineModels[i].txt_Model.Text = list_ymh_MachineName[i];
                                lsit_machineModels[i].txt_Model.Tag = "雅马哈贴片机";
                            }); 
                            continue; 
                        }
                        int Cycle = await ProductionCycle(ymh_Model[index].MachineName);
                        Dispatcher.Invoke(() =>
                        {
                            lsit_machineModels[i].txt_Model.Text = list_ymh_MachineName[index];//设备名称
                            lsit_machineModels[i].txt_Model.Tag = "雅马哈贴片机";
                            lsit_machineModels[i].txt_ProductName.Text = ymh_Model[index].ProductName;//产品名称
                            lsit_machineModels[i].txt_Cycle.Text = Cycle + "(ms)";//生产周期
                            lsit_machineModels[i].txt_Output.Text = ymh_Model[index].TotalQuantity + "(pcs)";//生产数量
                            lsit_machineModels[i].txt_OnTime.Text = OnTime[i];//开机时间
                            lsit_machineModels[i].txt_EquipmentAlm.Text = "0";//报警数量
                            lsit_machineModels[i].btn_Line.Content = "在线";
                            lsit_machineModels[i].btn_Line.Background = Brushes.Green;
                            lsit_machineModels[i].tb_Total.Visibility = Visibility.Visible;
                            lsit_machineModels[i].txt_Total.Visibility = Visibility.Visible;
                            lsit_machineModels[i].txt_Total.Text = list_Total[i] + "(pcs)";
                        });
                    }
                }
                catch (Exception ){continue;}
                
                await Task.Delay(3000);
            }
        }

        private async Task<int> ProductionCycle(string Name)
        {
            string select = $"SELECT *FROM (SELECT *,ROW_NUMBER() OVER (PARTITION BY TotalQuantity ORDER BY Time DESC ) AS rn " +
                            $"FROM ymh_Producedate WHERE CAST(Time AS DATE) = CAST(GETDATE() AS DATE) and MachineName='{Name}' and Cycle!='0' ) t WHERE rn = 1 order by Time asc";
            System.Data.DataTable dt = await database.SelectDataAsync(select);
            int Cycle = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Cycle += (int)(dt.Rows[i].ItemArray[4]);
            }
            return Cycle = Cycle / dt.Rows.Count;
        }
        private int ymh_IndexName(string gkgMachineName, List<ymh_model> ymh_Model)
        {
            for (int i = 0; i < ymh_Model.Count; i++)
            {
                if (gkgMachineName == ymh_Model[i].MachineName)
                {
                    return i;
                }
            }
            return -1;
        }

        private async Task<List<string>> ymh_MachineOnTime()
        {
            List<string> list_Time = new List<string>();
            TimeSpan timeSpan = TimeSpan.FromSeconds(0);
            for (int i = 0; i < list_ymh_MachineName.Count; i++)
            {
                timeSpan = TimeSpan.FromSeconds(0);
                List<ymh_model> list_ymh = new List<ymh_model>();
                await database.SelectDataAsync(list_ymh, "ymh_Producedate", "MachineName", list_ymh_MachineName[i]);
                for (int j = 0; j < list_ymh.Count; j++)
                {
                    try
                    {
                        if (list_ymh[j].RunningStatus != "运行中") continue;
                        if (list_ymh[j].Time == list_ymh[j - 1].Time) continue;
                        timeSpan += TimeSpan.Parse(list_ymh[j + 1].Time.Split(' ')[1]) - TimeSpan.Parse(list_ymh[j].Time.Split(' ')[1]);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                }
                int totalHours = (int)timeSpan.TotalHours;
                string formattedTime = $"{totalHours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}";
                list_Time.Add(formattedTime);
            }
            return list_Time;
        }

        private async Task<List<string>> ymh_Total()
        {
            List<string> list_Total = new List<string>();
            int TotalQuantity = 0;
            List<string> list_Name = await database.SelectColNameAsync("ymh_Producedate");
            list_Name.Sort();
            for (int i = 0; i < list_Name.Count; i++)
            {
                List<ymh_model> list_ymh = new List<ymh_model>();
                await database.SelectDataAsync(list_ymh, "ymh_Producedate", "MachineName", list_Name[i]);
                TotalQuantity = 0;
                for (int j = 1; j < list_ymh.Count; j++)
                {
                    try
                    {
                        if (list_ymh[j].TotalQuantity == "") continue;
                        if (list_ymh[j].TotalQuantity == "0") TotalQuantity += int.Parse(list_ymh[j - 1].TotalQuantity);
                        if (j == list_ymh.Count - 1) TotalQuantity += int.Parse(list_ymh[j].TotalQuantity);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
                list_Total.Add(TotalQuantity.ToString());
            }
            return list_Total;
        }
        #endregion

        #region  juki贴片机
        private async Task juki_DataUpdate()
        {
            while (VariableStorage.juki_Running) 
            {
                List<juki_model> juki_Models = new List<juki_model>();
                await database.SelectDataAsync(juki_Models);
                List<string> list_Name = await juki_MachineName(juki_Models);
                List<int> list_Total = new List<int>();
                List<string> OnTime = await juki_MachineOnTime(list_Total);

                for (int i = 0; i < list_juki_MachineName.Count; i++)
                {
                    int index = juki_IndexName(list_juki_MachineName[i], juki_Models);
                    if (index == -1) 
                    { 
                        Dispatcher.Invoke(() => 
                        { 
                            lsit_machineModels[i].txt_Model.Text = list_juki_MachineName[i];
                            lsit_machineModels[i].txt_Model.Tag = "JUKI贴片机";
                        }); 
                        continue; 
                    }
                    Dispatcher.Invoke(() =>
                    {
                        lsit_machineModels[i].txt_Model.Text = list_Name[i].Split(',')[0];
                        lsit_machineModels[i].txt_Model.Tag = "JUKI贴片机";
                        lsit_machineModels[i].txt_ProductName.Text = list_Name[i].Split(',')[1];//产品名称;
                        lsit_machineModels[i].txt_Cycle.Text = list_Name[i].Split(',')[2] + "(s)";//生产周期
                        lsit_machineModels[i].txt_Output.Text = list_Name[i].Split(',')[3] + "(pcs)";//生产数量
                        lsit_machineModels[i].txt_OnTime.Text = OnTime[i];//开机时间
                        lsit_machineModels[i].txt_EquipmentAlm.Text = "0";//报警数量
                        lsit_machineModels[i].btn_Line.Content = "在线";
                        lsit_machineModels[i].btn_Line.Background = Brushes.Green;
                        lsit_machineModels[i].tb_Total.Visibility = Visibility.Visible;
                        lsit_machineModels[i].txt_Total.Visibility = Visibility.Visible;
                        lsit_machineModels[i].txt_Total.Text = list_Total[i] + "(pcs)";
                    });
                }
                await Task.Delay(3000);
            }
        }

        private int juki_IndexName(string gkgMachineName, List<juki_model> juki_Models)
        {
            for (int i = 0; i < juki_Models.Count; i++)
            {
                if (gkgMachineName == juki_Models[i].MachineName)
                {
                    return i;
                }
            }
            return -1;
        }

        private async Task<List<string>> juki_MachineName(List<juki_model> juki_Models)
        {
            List<string> list_NameOne = new List<string>();
            List<string> list_Nametwe = new List<string>();
            List<string> list_MachineName = new List<string>();
            foreach (var juki in juki_Models)
            {
                if (juki.MachineName == "juki 1号机")
                {
                    list_NameOne.Add(juki.MachineName + "," + juki.StopTime + "," + juki.RunningTime + "," + juki.TotalPick);
                }
                else
                {
                    list_Nametwe.Add(juki.MachineName + "," + juki.StopTime + "," + juki.RunningTime + "," + juki.TotalPick);
                }
            }

            foreach (var juki in juki_Models)
            {
                try
                {
                    if (juki.MachineName == list_NameOne.Max().Split(',')[0] && juki.StopTime == list_NameOne.Max().Split(',')[1])
                    {
                        list_MachineName.Add(juki.MachineName + "," + juki.model + "," + juki.RunningTime + "," + juki.TotalPick);
                    }
                    else if (juki.MachineName == list_Nametwe.Max().Split(',')[0] && juki.StopTime == list_Nametwe.Max().Split(',')[1])
                    {
                        list_MachineName.Add(juki.MachineName + "," + juki.model + "," + juki.RunningTime + "," + juki.TotalPick);
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            list_MachineName.Sort();
            return list_MachineName;
        }

        private async Task<List<string>> juki_MachineOnTime(List<int> list_Total)
        {
            int total = 0;
            List<string> list_Time = new List<string>();
            List<juki_model> list_juki = new List<juki_model>();
            await database.SelectDataAsync(list_juki);
            TimeSpan CycleTime = TimeSpan.Parse("0");
            foreach (var juki in list_juki)
            {
                if (juki.MachineName == "juki 1号机")
                {
                    CycleTime += TimeSpan.Parse(juki.RunningTime);
                    total += juki.TotalPick;
                }
            }
            list_Total.Add(total);
            total = 0;
            int totalHours = (int)CycleTime.TotalHours;
            string formattedTime = $"{totalHours:D2}:{CycleTime.Minutes:D2}:{CycleTime.Seconds:D2}";
            list_Time.Add(formattedTime);
            CycleTime = TimeSpan.Parse("0");
            foreach (var juki in list_juki)
            {
                if (juki.MachineName == "juki 2号机")
                {
                    CycleTime += TimeSpan.Parse(juki.RunningTime);
                    total += juki.TotalPick;
                }
            }
            list_Total.Add(total);
            totalHours = (int)CycleTime.TotalHours;
            formattedTime = $"{totalHours:D2}:{CycleTime.Minutes:D2}:{CycleTime.Seconds:D2}";
            list_Time.Add(formattedTime);
            return list_Time;
        }
        #endregion
    }
}
